package com.链表.链表基础;

public class 单向链表_带哨兵 {
    private static class Node { // 节点类
        int value;//值
        Node next;//下一个节点

        public Node(int value, Node next) {
            this.value = value;
            this.next = next;
        }
    }
    private Node head = new Node(Integer.MIN_VALUE, null);

    // 根据索引获取节点
    private Node findNode(int index) {
        int i = -1;
        for(Node cur = this.head; cur != null; cur = cur.next,i++) {
            if(i == index){
                return cur;
            }
        }
        return null;
    }

    // 获取最后一个节点
    private Node findLast() {
        Node curr;
        for (curr = this.head; curr.next != null; ) {
            curr = curr.next;
        }
        return curr;
    }

    public void addLast(int value) {
        Node last = findLast();
        last.next = new Node(value, null);
    }

    public void insert(int index, int value) {
        Node prev = findNode(index-1);
        if(prev != null){
            prev.next = new Node(value, prev.next);
        }else {
            throw illegalIndex(index);
        }
    }

    public void remove(int index) {
        Node prev = findNode(index-1);
        Node curr;
        if(prev != null && (curr = prev.next) != null){
            prev.next = curr.next;
        }else {
            throw illegalIndex(index);
        }
    }

    public void addFirst(int value) {
        this.head.next = new Node(value, this.head.next);
    }

    private IllegalArgumentException illegalIndex(int index) {
        return new IllegalArgumentException(String.format("index [%d] 不合法%n", index));
    }
}
